<template>
  <v-dialog v-model="dialogVisible" max-width="450" persistent>
    <v-card>
      <v-card-title>{{ dialogTitle }}</v-card-title>

      <v-card-text>
        <v-text-field v-model="filterText" label="输入关键字过滤" prepend-inner-icon="mdi-magnify" clearable class="mb-4" />

        <v-list v-if="dialogVisible" class="menu-list" density="compact">
          <!-- 递归渲染菜单项 -->
          <template v-for="item in filteredMenuData" :key="item.id">
            <MenuListItem :item="item" :level="0" :selected-id="selectedNodeId" :expanded-nodes="expandedNodes"
              @select="handleSelect" @toggle="handleToggle" @load-children="loadNodeChildren" />
          </template>

          <!-- 加载状态 -->
          <v-list-item v-if="chooseLoading">
            <v-list-item-title>
              <v-progress-circular indeterminate size="16" class="mr-2" />
              加载中...
            </v-list-item-title>
          </v-list-item>

          <!-- 无数据状态 -->
          <v-list-item v-if="!chooseLoading && filteredMenuData.length === 0">
            <v-list-item-title class="text-grey">
              {{ filterText ? '无匹配数据' : '暂无数据' }}
            </v-list-item-title>
          </v-list-item>
        </v-list>
      </v-card-text>

      <v-card-actions>
        <v-spacer />
        <v-btn text @click="close">取消</v-btn>
        <v-btn color="primary" @click="save">确定</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { getTreeChooseLazy } from "@/api/system/menu/menuManagement";
import MenuListItem from './MenuListItem.vue';

interface MenuNode {
  id: string;
  menuName: string;
  children?: MenuNode[];
  isLeaf?: boolean;
  hasChildren?: boolean;
  [key: string]: any;
}

interface Props {
  modelValue?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: ''
});

const emit = defineEmits(['update:modelValue', 'menuChoose']);

// 响应式数据
const selfId = ref('');
const menuData = ref<MenuNode[]>([]);
const filterText = ref('');
const selectedNodeId = ref<string>('');
const selectedNode = ref<MenuNode | null>(null);
const expandedNodes = ref<Set<string>>(new Set());
const dialogTitle = ref('选择菜单');
const dialogVisible = ref(false);
const chooseLoading = ref(false);

// 过滤后的菜单数据
const filteredMenuData = computed(() => {
  if (!filterText.value) return menuData.value;

  const filterNodes = (nodes: MenuNode[]): MenuNode[] => {
    return nodes.filter(node => {
      const matchesFilter = node.menuName?.toLowerCase().includes(filterText.value.toLowerCase());
      const hasMatchingChildren = node.children ? filterNodes(node.children).length > 0 : false;

      if (matchesFilter || hasMatchingChildren) {
        return {
          ...node,
          children: node.children ? filterNodes(node.children) : undefined
        };
      }
      return false;
    }).map(node => typeof node === 'object' ? node : null).filter(Boolean) as MenuNode[];
  };


  console.log('过滤后的菜单数据:', menuData.value);

  return filterNodes(menuData.value);
});

// 显示菜单选择对话框
function showMenuChoose(id?: string) {
  selfId.value = id || '';
  selectedNodeId.value = '';
  selectedNode.value = null;
  expandedNodes.value.clear();
  dialogVisible.value = true;

  // 加载根节点数据
  loadRootNodes();
}

// 加载根节点数据
async function loadRootNodes() {
  chooseLoading.value = true;
  try {
    const { data } = await getTreeChooseLazy({
      parentId: props.modelValue || '0',
      id: selfId.value,
    });

    console.log('根节点数据:', data);
    menuData.value = data || [];
    //加到第一个
    menuData.value.unshift({
      id: '0',
      menuName: '根节点',
      children: []
    });

  } catch (error) {
    console.error('加载菜单数据失败:', error);
    menuData.value = [];
  } finally {
    chooseLoading.value = false;
  }
}

// 加载子节点数据
async function loadNodeChildren(nodeId: string) {
  try {
    const { data } = await getTreeChooseLazy({
      parentId: nodeId,
      id: selfId.value,
    });

    console.log(`节点 ${nodeId} 的子数据:`, data);

    // 查找并更新对应节点的children
    const updateNodeChildren = (nodes: MenuNode[]): MenuNode[] => {
      return nodes.map(node => {
        if (node.id === nodeId) {
          return { ...node, children: data || [] };
        }
        if (node.children) {
          return { ...node, children: updateNodeChildren(node.children) };
        }
        return node;
      });
    };

    menuData.value = updateNodeChildren(menuData.value);
  } catch (error) {
    console.error('加载子节点失败:', error);
  }
}

// 处理节点选择
function handleSelect(node: MenuNode) {
  selectedNodeId.value = node.id;
  selectedNode.value = node;
}

// 处理节点展开/折叠
function handleToggle(nodeId: string) {
  if (expandedNodes.value.has(nodeId)) {
    expandedNodes.value.delete(nodeId);
  } else {
    expandedNodes.value.add(nodeId);
  }
}

// 关闭对话框
function close() {
  dialogVisible.value = false;
  menuData.value = [];
  selectedNodeId.value = '';
  selectedNode.value = null;
  expandedNodes.value.clear();
  filterText.value = '';
  selfId.value = '';
}

// 保存选择
function save() {
  emit('menuChoose', selectedNode.value);
  close();
}

// 暴露方法给父组件
defineExpose({
  showMenuChoose
});
</script>

<style scoped>
.menu-list {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid rgba(0, 0, 0, 0.12);
  border-radius: 4px;
}

.menu-list .v-list-item {
  min-height: 36px;
}

.menu-list .v-list-item--active {
  background-color: rgba(25, 118, 210, 0.1);
  color: rgb(25, 118, 210);
}
</style>
